﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IMC.Prepare.Core;
using IMC.Prepare.Core.Domain.Localization;
using IMC.Prepare.Core.Data;
using IMC.Prepare.Core.Caching;

namespace IMC.Prepare.Services.Localization
{
    public partial class LocalizationService : ILocalizationService
    {
        #region Constants
        private const string LOCALSTRINGRESOURCES_ALL_KEY = "Nop.lsr.all-{0}";
        private const string LOCALSTRINGRESOURCES_BY_RESOURCENAME_KEY = "Nop.lsr.{0}-{1}";
        private const string LOCALSTRINGRESOURCES_PATTERN_KEY = "Nop.lsr.";
        #endregion

        private readonly IRepository<LocaleStringResource> _lsrRepository;
        private readonly IWorkContext _workContext;
        private readonly ICacheManager _cacheManager;

        public LocalizationService(ICacheManager cacheManager, IWorkContext workContext, 
            IRepository<LocaleStringResource> lsrRepository)
        {
            _cacheManager = cacheManager;
            _workContext = workContext;
            _lsrRepository = lsrRepository;
        }

        public virtual string GetResource(string resourceKey)
        {
            if (_workContext.WorkingLanguage != null)
                return GetResource(resourceKey, _workContext.WorkingLanguage.Id);

            return "";
        }

        public virtual string GetResource(string resourceKey, int languageId,
            bool logIfNotFound = true, string defaultValue = "", bool returnEmptyIfNotFound = false)
        {
            string result = string.Empty;
            var resourceKeyValue = resourceKey;
            if (resourceKeyValue == null)
                resourceKeyValue = string.Empty;
            resourceKeyValue = resourceKeyValue.Trim().ToLowerInvariant();
            //if (_localizationSettings.LoadAllLocaleRecordsOnStartup)
            //if (true)
            //{
                //load all records
                var resources = GetAllResourcesByLanguageId(languageId);

                if (resources.ContainsKey(resourceKeyValue))
                {
                    var lsr = resources[resourceKeyValue];
                    if (lsr != null)
                        result = lsr.ResourceValue;
                }
            //}
            //else
            //{
            //    //gradual loading
            //    //string key = string.Format(LOCALSTRINGRESOURCES_BY_RESOURCENAME_KEY, languageId, resourceKeyValue);
            //    //string lsr = _cacheManager.Get(key, () =>
            //    //{
            //        var query = from l in _lsrRepository.Table
            //                    where l.ResourceName == resourceKeyValue
            //                    && l.LanguageId == languageId
            //                    select l.ResourceValue;
            //        return query.FirstOrDefault();
            //    //});

            //    //if (lsr != null)
            //    //    result = lsr;
            //}
            if (String.IsNullOrEmpty(result))
            {
                //if (logIfNotFound)
                //    _logger.Warning(string.Format("Resource string ({0}) is not found. Language ID = {1}", resourceKey, languageId));

                if (!String.IsNullOrEmpty(defaultValue))
                {
                    result = defaultValue;
                }
                else
                {
                    if (!returnEmptyIfNotFound)
                        result = resourceKey;
                }
            }
            return result;
        }

        /// <summary>
        /// Gets all locale string resources by language identifier
        /// </summary>
        /// <param name="languageId">Language identifier</param>
        /// <returns>Locale string resource collection</returns>
        public virtual Dictionary<string, LocaleStringResource> GetAllResourcesByLanguageId(int languageId)
        {
            string key = string.Format(LOCALSTRINGRESOURCES_ALL_KEY, languageId);
            return _cacheManager.Get(key, () =>
            {
                var query = from l in _lsrRepository.Table
                            orderby l.ResourceName
                            where l.LanguageId == languageId
                            select l;
                var localeStringResourceDictionary =
                    query.ToDictionary(s => s.ResourceName.ToLowerInvariant());
                return localeStringResourceDictionary;
            });
        }
    }
}
